package com.ciban.smarthome.module.ui.adapter;

import java.io.IOException;
import java.io.InputStream;

import com.ciban.smarthome.R;
import com.ciban.smarthome.common.utils.RegexUtils;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

public class IconChooseAdapter extends BaseAdapter {

	private AssetManager assetManager;

	private String[] paths;
	private Context context;

	public IconChooseAdapter(Context context, String[] paths) {
		this.context = context;
		this.paths = paths;
	}

	@Override
	public int getCount() {
		return paths.length;
	}

	@Override
	public Object getItem(int position) {
		return paths[position];
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			convertView = View.inflate(context, R.layout.griditem_icon,
					null);
			holder = new ViewHolder();
			holder.iv_icon = (ImageView) convertView
					.findViewById(R.id.item_sceneicon_icon);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		if (RegexUtils.isNumStr(paths[position])) {
			holder.iv_icon.setImageResource(Integer.parseInt(paths[position]));
		} else {
			if (assetManager == null)
				assetManager = context.getAssets();
			InputStream in = null;
			Bitmap bmp = null;
			try {
				in = assetManager.open(paths[position]);
				bmp = BitmapFactory.decodeStream(in);
				holder.iv_icon.setImageBitmap(bmp);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (in != null)
						in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return convertView;
	}

	static class ViewHolder {
		ImageView iv_icon;
	}
}
